package com.tensquare.friend.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取request中到token
        String jwtAuthorization = request.getHeader("JwtAuthorization");
        if (jwtAuthorization != null && !"".equals(jwtAuthorization)) {
            // 不为空进行下一步处理
            if (jwtAuthorization.startsWith("Bearer ")) {
                // 如果是Bearer+空格开头，继续下一步处理
                // 截取从7位后的字符串
                final String token = jwtAuthorization.substring(7);
                // 解析获取载体
                Claims claims = null;
                try {
                    claims = this.jwtUtil.parseJWT(token);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (claims != null && !"".equals(claims)) {
                    // 不为空
                    if ("admin".equals(claims.get("roles"))) {
                        // admin角色
                        request.setAttribute("admin_claims", claims);
                    }
                    if ("user".equals(claims.get("roles"))) {
                        // user角色
                        request.setAttribute("user_claims", claims);
                    }
                }


            }


        }
        return true;
    }
}
